#include "teamadd.h"
#include "ui_teamadd.h"
#include <QScrollArea>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QDebug>
#include "playerradio.h"


teamAdd::teamAdd(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::teamAdd)
{
    ui->setupUi(this);

    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(addTeamToDb()));
    pullPlayers();
    prepareLayout();

}

teamAdd::~teamAdd()
{
    delete ui;
}

void teamAdd::prepareLayout() {

    QRect *rect = new QRect;



   rect->setHeight(800);
   rect->setWidth(100);

    rect = &(ui->scwc->childrenRect());
    rect->setHeight(rect->height() + 30);
    ui->scwc->setGeometry(*rect);



}

void teamAdd::pullPlayers() {

    QSqlDatabase appDb = QSqlDatabase::addDatabase("QSQLITE");
    appDb.setDatabaseName("/sdcard/basedata/base.db.sqlite");
    appDb.open();
    // qDebug() << appDb.lastError().text();


    QSqlQuery query("Select * from players");

     while(query.next()) {
         PlayerRadio *radiobutton = new PlayerRadio(this);
         QString text = QString("%1 %2 - %3").arg(query.value(0).toString()).arg(query.value(2).toString()).arg(query.value(3).toString());
         radiobutton->setText(text);
         radiobutton->setU_id(query.value(4).toInt());
         radio_list.append(radiobutton);
         ui->verticalLayout->addWidget(radiobutton);
    }
}

void teamAdd::addTeamToDb() {

    int last_team_id;

    QSqlDatabase appDb = QSqlDatabase::addDatabase("QSQLITE");
    appDb.setDatabaseName("/sdcard/basedata/base.db.sqlite");
    appDb.open();
    // qDebug() << appDb.lastError().text();


    QSqlQuery query("CREATE TABLE IF NOT EXISTS teams(team_name varchar(30), t_id  INTEGER PRIMARY KEY AUTOINCREMENT)");

    query.prepare("CREATE TABLE IF NOT EXISTS team_player_relation(team_id int, player_id int)");
    query.exec();

    query.prepare("select t_id from teams where t_id = (select max(t_id) from teams)");
    query.exec();
    query.next();

    if (query.value(0).toInt() < 1) {

        last_team_id = 0;

    } else {

        last_team_id = query.value(0).toInt() ;
    }

    last_team_id++;

    QString query_string = QString("Insert into teams values('%1','%2')").arg(ui->lineEdit->text()).arg(last_team_id);

    query.prepare(query_string);
    query.exec();

    foreach(PlayerRadio *each_player, radio_list) {
        if(each_player->isChecked())  {
            QString query_string = QString("insert into team_player_relation values('%1','%2')").arg(last_team_id).arg(each_player->getU_id());
            query.prepare(query_string);
            query.exec();
        }

    }
    close();
}
